Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Text
Imports System.Windows.Forms

Namespace FileTransferProfileApplication

    Partial Public Class Form1
        Inherits Form

#Region "Private Fields"

        Private devList As List(Of C4F.DevKit.Bluetooth.ServiceAndDeviceDiscovery.Device) = Nothing
        Private FTPService As C4F.DevKit.Bluetooth.ServiceAndDeviceDiscovery.RemoteService = Nothing
        Private networkStream As Net.Sockets.NetworkStream = Nothing
        Private FTPServiceList As List(Of C4F.DevKit.Bluetooth.ServiceAndDeviceDiscovery.RemoteService)
        Private selectedNode As TreeNode
        Private isAsync As Boolean = True

#End Region

#Region "Constructor"

        ''' <summary>
        ''' Initializes the form
        ''' </summary>
        Public Sub New()

            InitializeComponent()

        End Sub

#End Region

#Region "EventHandlers"

        ' Event Handler for btnDiscover. Performs Device Discovery.
        Private Sub btnDiscover_Click(ByVal sender As Object, ByVal e As EventArgs) _
                                     Handles btnDiscover.Click

            Try

                cmbDevice.Items.Clear()
                cmbServices.Items.Clear()
                cmbDevice.Text = ""
                cmbServices.Text = ""
                cmbServices.Enabled = False
                btnConnect.Enabled = False
                btnOperation.Enabled = False
                tvFolderHierarchy.Nodes.Clear()
                txtCurrentDirectory.Text = ""
                btnRefreshFold.Enabled = False

                Me.Cursor = Cursors.WaitCursor
                devList = deviceServicesManager1.DiscoverAllDevices()
                If devList.Count <> 0 Then

                    For Each dev As C4F.DevKit.Bluetooth.ServiceAndDeviceDiscovery.Device In devList
                        cmbDevice.Items.Add(dev.Name)
                    Next

                End If

                If devList.Count > 0 Then

                    cmbServices.Enabled = True
                End If

            Catch ex As Exception

                Dim errorMsg As String = ex.Message
                If ex.InnerException IsNot Nothing Then
                    errorMsg += Environment.NewLine & ex.InnerException.Message
                End If

                Microsoft.VisualBasic.MsgBox("Unable to discover devices. " & errorMsg, _
                                             Microsoft.VisualBasic.MsgBoxStyle.Critical, _
                                             "FileTransferProfile Application")

            Finally
                Me.Cursor = Cursors.Default
            End Try

        End Sub

        ' Event Handler for cmbServices.Performs service discovery on 
        ' selected device. Searches only for File Transfer Service.
        Private Sub cmbServices_Enter(ByVal sender As Object, ByVal e As EventArgs) _
                                                            Handles cmbServices.Enter

            Try
                cmbServices.Items.Clear()
                If devList IsNot Nothing AndAlso devList.Count <> 0 Then

                    For Each dev As C4F.DevKit.Bluetooth.ServiceAndDeviceDiscovery.Device In devList

                        If dev.Name = cmbDevice.Text Then
                            FTPServiceList = deviceServicesManager1.DiscoverServicesByType _
                            (dev, C4F.DevKit.Bluetooth.ServiceAndDeviceDiscovery.ServiceType.OBEXFileTransfer)

                            If FTPServiceList IsNot Nothing AndAlso FTPServiceList.Count <> 0 Then

                                For Each remServ As C4F.DevKit.Bluetooth.ServiceAndDeviceDiscovery.RemoteService _
                                                                                                        In FTPServiceList
                                    cmbServices.Items.Add(remServ.Name)
                                Next

                            End If

                            Exit For

                        End If

                    Next

                End If

                If cmbServices.Items.Count > 0 Then
                    btnConnect.Enabled = True
                End If

            Catch ex As Exception

                btnConnect.Enabled = False
                cmbServices.Enabled = True
                tvFolderHierarchy.Enabled = False

                Dim errorMsg As String = ex.Message

                If ex.InnerException IsNot Nothing Then
                    errorMsg += ex.InnerException.Message
                End If

                Microsoft.VisualBasic.MsgBox("Unable to discover services on remote device. " & _
                                             errorMsg, Microsoft.VisualBasic.MsgBoxStyle.Critical, _
                                             "FileTransferProfile Application")
            End Try

        End Sub

        ' Event Handler for btnConnect.Connects to the remote device.
        Private Sub btnConnect_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnConnect.Click

            Try

                Me.Cursor = Cursors.WaitCursor

                If String.IsNullOrEmpty(cmbServices.Text) Then
                    Microsoft.VisualBasic.MsgBox("Please select a service for performing File Transfer operations.", _
                                                 Microsoft.VisualBasic.MsgBoxStyle.Critical, "FileTransferProfile Application")
                    cmbServices.Focus()

                Else

                    For Each remote As C4F.DevKit.Bluetooth.ServiceAndDeviceDiscovery.RemoteService In FTPServiceList

                        If cmbServices.Text = remote.Name Then

                            FTPService = remote
                            networkStream = FTPService.Connect()
                            btnConnect.Enabled = False
                            cmbServices.Enabled = False
                            tvFolderHierarchy.Enabled = True
                            btnOperation.Enabled = True
                            btnRefreshFold.Enabled = True
                            ftpManager1.NetworkStream = networkStream
                            ' Initializes the event handlers
                            ftpManager1.Connect()
                            ' Get the folder listing of the remote device.
                            Dim node As New TreeNode("\")
                            node.Tag = "folder"
                            tvFolderHierarchy.Nodes.Add(node)
                            Exit For

                        End If

                    Next

                End If

            Catch servEx As C4F.DevKit.Bluetooth.ServiceAndDeviceDiscovery.ServiceConnectionException

                btnConnect.Enabled = True
                cmbServices.Enabled = True
                tvFolderHierarchy.Enabled = False

                Dim errorMsg As String = servEx.Message
                If servEx.InnerException IsNot Nothing Then
                    errorMsg += servEx.InnerException.Message
                End If

                Microsoft.VisualBasic.MsgBox(errorMsg, Microsoft.VisualBasic.MsgBoxStyle.Critical, _
                                             "FileTransferProfile Application")

            Catch ftpEx As C4F.DevKit.Bluetooth.FileTransferProfile.FTPException

                btnConnect.Enabled = True
                cmbServices.Enabled = True
                tvFolderHierarchy.Enabled = False

                Dim errorMsg As String = ftpEx.Message
                If ftpEx.InnerException IsNot Nothing Then
                    errorMsg += ftpEx.InnerException.Message
                End If

                Microsoft.VisualBasic.MsgBox(errorMsg, Microsoft.VisualBasic.MsgBoxStyle.Critical, _
                                             "FileTransferProfile Application")

            Catch ex As Exception

                btnConnect.Enabled = True
                cmbServices.Enabled = True
                tvFolderHierarchy.Enabled = False
                Dim errorMsg As String = ex.Message

                If ex.InnerException IsNot Nothing Then
                    errorMsg += ex.InnerException.Message
                End If

                Microsoft.VisualBasic.MsgBox(errorMsg, Microsoft.VisualBasic.MsgBoxStyle.Critical, _
                                             "FileTransferProfile Application")

            Finally
                Me.Cursor = Cursors.Default
            End Try

        End Sub

        ' Event Handler for SetCurrentDirectoryCompleted event.
        Private Sub ftpManager1_SetCurrentDirectoryCompleted _
                                    (ByVal sender As Object, _
                                     ByVal e As C4F.DevKit.Bluetooth.FileTransferProfile.SetCurrentDirectoryCompletedEventArgs) _
                                     Handles ftpManager1.SetCurrentDirectoryCompleted

            If isAsync Then
            Else
                isAsync = True
            End If

        End Sub

        ' Event Handler for SendFolderCompleted event.
        Private Sub ftpManager1_SendFolderCompleted _
        (ByVal sender As Object, ByVal e As C4F.DevKit.Bluetooth.FileTransferProfile.SendFolderCompletedEventArgs) _
        Handles ftpManager1.SendFolderCompleted

            If isAsync Then

                If e.Error Is Nothing Then

                    Microsoft.VisualBasic.MsgBox("Asynchronous Send Folder Operation Completed. " _
                                                 & Environment.NewLine & "Folder Name:" _
                                                 & e.LocalFolderPath, Microsoft.VisualBasic.MsgBoxStyle.Information, _
                                                 "FileTransferProfile Application")
                    ftpManager1.SetCurrentDirectory(txtCurrentDirectory.Text)
                Else

                    Dim errorMsg As String = e.Error.Message
                    If e.Error.InnerException IsNot Nothing Then
                        errorMsg += Environment.NewLine & e.Error.InnerException.Message
                    End If

                    Microsoft.VisualBasic.MsgBox(errorMsg, Microsoft.VisualBasic.MsgBoxStyle.Critical, _
                                                 "FileTransferProfile Application")

                End If

            Else

                If e.Error Is Nothing Then
                    ftpManager1.SetCurrentDirectory(txtCurrentDirectory.Text)
                End If

                isAsync = True
            End If

        End Sub

        ' Event Handler for SendFileCompleted event.
        Private Sub ftpManager1_SendFileCompleted _
        (ByVal sender As Object, ByVal e As C4F.DevKit.Bluetooth.FileTransferProfile.SendFileCompletedEventArgs) _
        Handles ftpManager1.SendFileCompleted

            If isAsync Then

                If e.Error Is Nothing Then
                    Microsoft.VisualBasic.MsgBox("Asynchronous Send File Operation Completed. " _
                                                 & Environment.NewLine & "File Name:" & e.LocalFilePath, _
                                                 Microsoft.VisualBasic.MsgBoxStyle.Information, "FileTransferProfile Application")
                Else
                    Dim errorMsg As String = e.Error.Message
                    If e.Error.InnerException IsNot Nothing Then
                        errorMsg += Environment.NewLine & e.Error.InnerException.Message
                    End If

                    Microsoft.VisualBasic.MsgBox(errorMsg, Microsoft.VisualBasic.MsgBoxStyle.Critical, _
                                                 "FileTransferProfile Application")

                End If

            Else
                isAsync = True
            End If

        End Sub

        ' Event Handler for GetFolderCompleted event.
        Private Sub ftpManager1_GetFolderCompleted _
        (ByVal sender As Object, ByVal e As C4F.DevKit.Bluetooth.FileTransferProfile.GetFolderCompletedEventArgs) _
        Handles ftpManager1.GetFolderCompleted

            If isAsync Then

                If e.Error Is Nothing Then
                    Microsoft.VisualBasic.MsgBox("Asynchronous Get Folder Operation Completed. " _
                                                 & Environment.NewLine & "Folder Name:" _
                                                 & e.RemoteFolderPath, _
                                                 Microsoft.VisualBasic.MsgBoxStyle.Information, "FileTransferProfile Application")

                Else
                    Dim errorMsg As String = "An Asynchronous Get Folder Operation has failed. Error details: " & e.Error.Message

                    If e.Error.InnerException IsNot Nothing Then
                        errorMsg += Environment.NewLine & e.Error.InnerException.Message
                    End If

                    Microsoft.VisualBasic.MsgBox(errorMsg, Microsoft.VisualBasic.MsgBoxStyle.Critical, _
                                                 "FileTransferProfile Application")
                End If

            Else
                isAsync = True
            End If

            ' txtCurrentDirectory.Text = e.RemoteFolderPath;
        End Sub

        ' Event Handler for GetFileCompleted event.
        Private Sub ftpManager1_GetFileCompleted _
        (ByVal sender As Object, ByVal e As C4F.DevKit.Bluetooth.FileTransferProfile.GetFileCompletedEventArgs) _
        Handles ftpManager1.GetFileCompleted

            If isAsync Then

                If e.Error Is Nothing Then

                    Try

                        If Not String.IsNullOrEmpty(folderBrowserDialog1.SelectedPath) Then
                            IO.File.WriteAllBytes(folderBrowserDialog1.SelectedPath & "\" _
                                                  & e.RemoteFilePath.Substring _
                                                  (e.RemoteFilePath.LastIndexOf("\"c) + 1), e.FileContent)


                            ' string dir = e.RemoteFilePath;
                            ' dir = dir.Substring(0, dir.LastIndexOf("\\"));
                            ' txtCurrentDirectory.Text = e.RemoteFolderPath;
                            Microsoft.VisualBasic.MsgBox("Asynchronous Get File Operation Completed. " _
                                                         & Environment.NewLine & "File Name:" & e.RemoteFilePath, _
                                                         Microsoft.VisualBasic.MsgBoxStyle.Information, _
                                                         "FileTransferProfile Application")
                        End If

                    Catch ex As Exception

                        Dim errorMsg As String = "An Asynchronous Get File Operation has failed. Error details: " & ex.Message
                        If ex.InnerException IsNot Nothing Then
                            errorMsg += Environment.NewLine & ex.InnerException.Message
                        End If

                        ' txtCurrentDirectory.Text = e.RemoteFolderPath;
                        Microsoft.VisualBasic.MsgBox(errorMsg, Microsoft.VisualBasic.MsgBoxStyle.Critical, _
                                                     "FileTransferProfile Application")
                    End Try

                Else

                    Dim errorMsg As String = "An Asynchronous Get File Operation has failed. Error details: " & e.Error.Message
                    If e.Error.InnerException IsNot Nothing Then
                        errorMsg += Environment.NewLine & e.Error.InnerException.Message
                    End If

                    Microsoft.VisualBasic.MsgBox(errorMsg, Microsoft.VisualBasic.MsgBoxStyle.Critical, _
                                                 "FileTransferProfile Application")
                End If

            Else
                isAsync = True
            End If

        End Sub

        ' Event Handler for DeleteFolderCompleted event.
        Private Sub ftpManager1_DeleteFolderCompleted _
        (ByVal sender As Object, ByVal e As C4F.DevKit.Bluetooth.FileTransferProfile.DeleteFolderCompletedEventArgs) _
        Handles ftpManager1.DeleteFolderCompleted

            If isAsync Then

                If e.Error Is Nothing Then
                    Microsoft.VisualBasic.MsgBox("Asynchronous Delete Folder Operation Completed. " _
                                                 & Environment.NewLine & "Folder Name:" & e.RemoteFolderPath, _
                                                 Microsoft.VisualBasic.MsgBoxStyle.Information, _
                                                 "FileTransferProfile Application")
                    Dim dir As String = e.RemoteFolderPath
                    dir = dir.Substring(0, dir.LastIndexOf("\"))
                    txtCurrentDirectory.Text = dir
                Else
                    Dim errorMsg As String = "An Asynchronous Delete Folder Operation has failed. Error details: " & e.Error.Message
                    If e.Error.InnerException IsNot Nothing Then
                        errorMsg += Environment.NewLine & e.Error.InnerException.Message
                    End If

                    Microsoft.VisualBasic.MsgBox(errorMsg, Microsoft.VisualBasic.MsgBoxStyle.Critical, _
                                                 "FileTransferProfile Application")
                    txtCurrentDirectory.Text = e.RemoteFolderPath
                End If

            Else

                If e.Error Is Nothing Then
                    Dim dir As String = e.RemoteFolderPath
                    dir = dir.Substring(0, dir.LastIndexOf("\"))
                    txtCurrentDirectory.Text = e.RemoteFolderPath
                Else
                    txtCurrentDirectory.Text = e.RemoteFolderPath
                End If

                isAsync = True
            End If

        End Sub

        ' Event Handler for DeleteFileCompleted event.
        Private Sub ftpManager1_DeleteFileCompleted _
        (ByVal sender As Object, ByVal e As C4F.DevKit.Bluetooth.FileTransferProfile.DeleteFileCompletedEventArgs) _
        Handles ftpManager1.DeleteFileCompleted

            If isAsync Then

                If e.Error Is Nothing Then
                    Microsoft.VisualBasic.MsgBox("Asynchronous Delete File Operation Completed. " _
                                                 & Environment.NewLine & "File Name:" & e.RemoteFilePath, _
                                                 Microsoft.VisualBasic.MsgBoxStyle.Information, _
                                                 "FileTransferProfile Application")
                Else

                    Dim errorMsg As String = "An Asynchronous Delete File Operation has failed. Error details: " _
                                             & e.Error.Message
                    If e.Error.InnerException IsNot Nothing Then
                        errorMsg += Environment.NewLine & e.Error.InnerException.Message
                    End If

                    Microsoft.VisualBasic.MsgBox(errorMsg, Microsoft.VisualBasic.MsgBoxStyle.Critical, _
                                                 "FileTransferProfile Application")
                End If

            Else
                isAsync = True
            End If

        End Sub

        ' Event Handler for CreateFolderCompleted event.
        Private Sub ftpManager1_CreateFolderCompleted _
        (ByVal sender As Object, ByVal e As C4F.DevKit.Bluetooth.FileTransferProfile.CreateFolderCompletedEventArgs) _
            Handles ftpManager1.CreateFolderCompleted

            If isAsync Then

                If e.Error Is Nothing Then
                    Microsoft.VisualBasic.MsgBox("Asynchronous Create Folder Operation Completed. " _
                                                 & Environment.NewLine & "Folder Name:" & e.RemoteFolderPath, _
                                                 Microsoft.VisualBasic.MsgBoxStyle.Information, _
                                                 "FileTransferProfile Application")

                    ftpManager1.SetCurrentDirectory(txtCurrentDirectory.Text)
                Else

                    Dim errorMsg As String = "An Asynchronous Create Folder Operation has failed. Error details: " _
                                             & e.Error.Message
                    If e.Error.InnerException IsNot Nothing Then
                        errorMsg += Environment.NewLine & e.Error.InnerException.Message
                    End If
                    Microsoft.VisualBasic.MsgBox(errorMsg, Microsoft.VisualBasic.MsgBoxStyle.Critical, _
                                                 "FileTransferProfile Application")
                End If

            Else

                If e.Error Is Nothing Then
                    ftpManager1.SetCurrentDirectory(txtCurrentDirectory.Text)
                End If

                isAsync = True
            End If

        End Sub

        ' Event Handler for Form Load event.
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) _
        Handles MyBase.Load

            cmbDevice.Items.Clear()
            cmbServices.Items.Clear()
            cmbDevice.Text = ""
            cmbServices.Text = ""
            cmbServices.Enabled = False
            btnConnect.Enabled = False
            btnOperation.Enabled = False
            tvFolderHierarchy.Nodes.Clear()
            txtCurrentDirectory.Text = ""
            btnRefreshFold.Enabled = False
            Try

                devList = deviceServicesManager1.DiscoverAllDevices()

                If devList.Count <> 0 Then

                    For Each dev As C4F.DevKit.Bluetooth.ServiceAndDeviceDiscovery.Device In devList
                        cmbDevice.Items.Add(dev.Name)
                    Next

                End If

                If devList.Count > 0 Then
                    cmbServices.Enabled = True
                End If

            Catch ex As Exception

                Dim errorMsg As String = ex.Message

                If ex.InnerException IsNot Nothing Then
                    errorMsg += Environment.NewLine & ex.InnerException.Message
                End If

                Microsoft.VisualBasic.MsgBox("Unable to discover devices." _
                                             & errorMsg, Microsoft.VisualBasic.MsgBoxStyle.Critical, _
                                             "FileTransferProfile Application")
            End Try

        End Sub

        ' Event Handler for Tree view NodeMouseClick event.
        Private Sub tvFolderHierarchy_NodeMouseClick(ByVal sender As Object, ByVal e As TreeNodeMouseClickEventArgs) _
                                                                        Handles tvFolderHierarchy.NodeMouseClick

            If e.Button = Windows.Forms.MouseButtons.Right Then
                selectedNode = e.Node
                With contextMenuStrip1
                    .Items.Clear()
                    .Items.Add("Pull Sync")
                    .Items.Add("Pull Async")
                    .Items.Add("Delete Sync")
                    .Items.Add("Delete Async")

                    If e.Node.Tag.ToString() = "folder" Then
                        ' Add create folder options
                        .Items.Add("Create SubFolder Sync")

                        .Items.Add("Create SubFolder Async")
                    End If

                    .Show()
                End With
                selectedNode.ContextMenuStrip = contextMenuStrip1
            Else

                selectedNode = e.Node
                Me.Cursor = Cursors.WaitCursor
                If e.Node.Tag.ToString() = "folder" Then

                    If e.Node.GetNodeCount(False) > 0 Then
                        e.Node.Nodes.Clear()
                    End If

                    GetFolderListing(e.Node.FullPath)
                End If

                Me.Cursor = Cursors.Default
            End If

        End Sub

        ' Event Handler for contextMenuStrip1 ItemClicked event.
        Private Sub contextMenuStrip1_ItemClicked(ByVal sender As Object, _
                                                   ByVal e As ToolStripItemClickedEventArgs) _
                                                   Handles contextMenuStrip1.ItemClicked
            Dim selectedCommand As String = e.ClickedItem.Text
            selectedNode.ContextMenuStrip = Nothing
            contextMenuStrip1.Hide()
            Me.Cursor = Cursors.WaitCursor

            Try

                Select Case selectedCommand

                    Case "Pull Sync"
                        isAsync = False

                        If folderBrowserDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
                            isAsync = False

                            If selectedNode.Tag.ToString() = "folder" Then

                                Try

                                    If Not String.IsNullOrEmpty(selectedNode.FullPath) _
                                    AndAlso Not String.IsNullOrEmpty(folderBrowserDialog1.SelectedPath) Then

                                        ftpManager1.GetFolder(selectedNode.FullPath, folderBrowserDialog1.SelectedPath)
                                        Microsoft.VisualBasic.MsgBox("Synchronous Get Folder Operation Completed. " _
                                                                     & Environment.NewLine & "Received Folder: " _
                                                                     & selectedNode.FullPath, _
                                                                     Microsoft.VisualBasic.MsgBoxStyle.Information, _
                                                                     "FileTransferProfile Application")

                                    End If

                                Catch ex As Exception

                                    Dim errorMsg As String = "A Synchronous Get Folder Operation has failed. Error details: " _
                                                             & ex.Message
                                    If ex.InnerException IsNot Nothing Then
                                        errorMsg += ex.InnerException.Message
                                    End If

                                    Microsoft.VisualBasic.MsgBox(errorMsg, Microsoft.VisualBasic.MsgBoxStyle.Critical, _
                                                                 "FileTransferProfile Application")
                                End Try

                            Else

                                Try

                                    If Not String.IsNullOrEmpty(selectedNode.FullPath) _
                                    AndAlso Not String.IsNullOrEmpty(folderBrowserDialog1.SelectedPath) Then

                                        IO.File.WriteAllBytes(folderBrowserDialog1.SelectedPath & "\" _
                                                              & selectedNode.Text, ftpManager1.GetFile _
                                                              (selectedNode.FullPath))
                                        Microsoft.VisualBasic.MsgBox("Synchronous Get File Operation Completed. " _
                                                                     & Environment.NewLine & "Received File: " _
                                                                     & selectedNode.FullPath, _
                                                                     Microsoft.VisualBasic.MsgBoxStyle.Information, _
                                                                     "FileTransferProfile Application")
                                    End If

                                Catch ex As Exception

                                    Dim errorMsg As String = "A Synchronous Get File Operation has failed. Error details: " _
                                                            & ex.Message
                                    If ex.InnerException IsNot Nothing Then
                                        errorMsg += ex.InnerException.Message
                                    End If

                                    Microsoft.VisualBasic.MsgBox(errorMsg, Microsoft.VisualBasic.MsgBoxStyle.Critical, _
                                                                 "FileTransferProfile Application")
                                End Try

                            End If

                        End If

                        Exit Select

                    Case "Pull Async"

                        If selectedNode.Tag.ToString() = "folder" Then

                            If folderBrowserDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then

                                If Not String.IsNullOrEmpty(selectedNode.FullPath) _
                                AndAlso Not String.IsNullOrEmpty(folderBrowserDialog1.SelectedPath) Then
                                    ftpManager1.GetFolderAsync(selectedNode.FullPath, _
                                                               folderBrowserDialog1.SelectedPath, Nothing)
                                End If

                            End If

                        Else

                            If folderBrowserDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then

                                If Not String.IsNullOrEmpty(selectedNode.FullPath) _
                                AndAlso Not String.IsNullOrEmpty(folderBrowserDialog1.SelectedPath) Then
                                    ftpManager1.GetFileAsync(selectedNode.FullPath, Nothing)
                                End If

                            End If

                        End If

                        Exit Select

                    Case "Delete Sync"
                        isAsync = False

                        If selectedNode.Tag.ToString() = "folder" Then

                            Try

                                If Not String.IsNullOrEmpty(selectedNode.FullPath) Then

                                    ftpManager1.DeleteFolder(selectedNode.FullPath, True)
                                    Microsoft.VisualBasic.MsgBox("Synchronous Delete Folder Operation Completed. " _
                                                                 & Environment.NewLine & "Deleted Folder: " _
                                                                 & selectedNode.FullPath, _
                                                                 Microsoft.VisualBasic.MsgBoxStyle.Information, _
                                                                 "FileTransferProfile Application")

                                End If

                            Catch ex As Exception

                                Dim errorMsg As String = "A Synchronous Delete Folder Operation has failed. Error details: " _
                                                        & ex.Message
                                If ex.InnerException IsNot Nothing Then
                                    errorMsg += ex.InnerException.Message
                                End If

                                Microsoft.VisualBasic.MsgBox(errorMsg, Microsoft.VisualBasic.MsgBoxStyle.Critical, _
                                                             "FileTransferProfile Application")
                            End Try

                        Else

                            Try

                                If Not String.IsNullOrEmpty(selectedNode.FullPath) Then
                                    ftpManager1.DeleteFile(selectedNode.FullPath)
                                    Microsoft.VisualBasic.MsgBox("Synchronous Delete File Operation Completed. " _
                                                                 & Environment.NewLine & "Deleted File: " _
                                                                 & selectedNode.FullPath, _
                                                                 Microsoft.VisualBasic.MsgBoxStyle.Information, _
                                                                 "FileTransferProfile Application")
                                End If

                            Catch ex As Exception

                                Dim errorMsg As String = "A Synchronous Delete File Operation has failed. Error details: " _
                                                         & ex.Message

                                If ex.InnerException IsNot Nothing Then
                                    errorMsg += ex.InnerException.Message
                                End If

                                Microsoft.VisualBasic.MsgBox(errorMsg, Microsoft.VisualBasic.MsgBoxStyle.Critical, _
                                                             "FileTransferProfile Application")
                            End Try

                        End If

                        Exit Select
                    Case "Delete Async"

                        If selectedNode.Tag.ToString() = "folder" Then

                            If Not String.IsNullOrEmpty(selectedNode.FullPath) Then
                                ftpManager1.DeleteFolderAsync(selectedNode.FullPath, True, Nothing)
                            End If

                        Else

                            If Not String.IsNullOrEmpty(selectedNode.FullPath) Then
                                ftpManager1.DeleteFileAsync(selectedNode.FullPath, Nothing)
                            End If

                        End If

                        Exit Select

                    Case "Create SubFolder Sync"

                        Try
                            isAsync = False
                            If selectedNode.Tag.ToString() = "folder" Then

                                Dim folderName As String = ""
                                Do
                                    folderName = Microsoft.VisualBasic.Interaction.InputBox _
                                    ("Enter a folder name. ", "Create Folder", "Folder1", 200, 200)

                                    If folderName = "Folder1" OrElse folderName = String.Empty Then
                                        Exit Do
                                    End If

                                Loop While String.IsNullOrEmpty(folderName.Trim())

                                If Not String.IsNullOrEmpty(folderName.Trim()) Then

                                    If Not String.IsNullOrEmpty(selectedNode.FullPath) Then
                                        ftpManager1.CreateFolder(selectedNode.FullPath & "\" _
                                                                 & folderName, True)
                                        Microsoft.VisualBasic.MsgBox("Synchronous Create Folder Operation Completed. " _
                                                                     & Environment.NewLine & "Created Folder: " _
                                                                     & folderName & " At location " & selectedNode.FullPath _
                                                                     & " on remote device.", _
                                                                     Microsoft.VisualBasic.MsgBoxStyle.Information, _
                                                                     "FileTransferProfile Application")
                                    End If

                                End If

                            End If

                        Catch ex As Exception

                            Dim errorMsg As String = "A Synchronous Create Folder Operation has failed. Error details: " _
                                                     & ex.Message
                            If ex.InnerException IsNot Nothing Then
                                errorMsg += ex.InnerException.Message
                            End If

                            Microsoft.VisualBasic.MsgBox(errorMsg, Microsoft.VisualBasic.MsgBoxStyle.Critical, _
                                                         "FileTransferProfile Application")
                        End Try

                        Exit Select

                    Case "Create SubFolder Async"

                        If selectedNode.Tag.ToString() = "folder" Then
                            Dim folderName As String = ""
                            Do
                                folderName = Microsoft.VisualBasic.Interaction.InputBox("Enter a folder name. ", _
                                                                                        "Create Folder", "Folder1", 200, 200)
                                If folderName = "Folder1" OrElse folderName = String.Empty Then
                                    Exit Do

                                End If

                            Loop While String.IsNullOrEmpty(folderName.Trim())
                            If Not String.IsNullOrEmpty(folderName.Trim()) Then

                                If Not String.IsNullOrEmpty(selectedNode.FullPath) Then
                                    ftpManager1.CreateFolderAsync(selectedNode.FullPath & "\" & folderName, True, Nothing)
                                End If

                            End If

                        End If

                        Exit Select

                End Select

            Finally
                Me.Cursor = Cursors.Default
            End Try

        End Sub

        ' Event Handler for btnOperation Click event.Performs the Push Operations.
        Private Sub btnOperation_Click(ByVal sender As Object, ByVal e As EventArgs) _
                                                                        Handles btnOperation.Click

            Select Case cmbPushOperations.Text
                Case "Push File Sync"

                    Try

                        isAsync = False
                        If openFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then

                            If Not String.IsNullOrEmpty(openFileDialog1.FileName) Then

                                ftpManager1.SendFile(openFileDialog1.FileName)
                                Microsoft.VisualBasic.MsgBox("Synchronous Send File Operation Completed." _
                                                             & Environment.NewLine & "Pushed File: " _
                                                             & openFileDialog1.FileName, _
                                                             Microsoft.VisualBasic.MsgBoxStyle.Information, _
                                                             "FileTransferProfile Application")
                            End If

                        End If

                    Catch ex As Exception

                        Dim errorMsg As String = "A Synchronous Send File Operation has failed. Error details: " _
                                                 & ex.Message

                        If ex.InnerException IsNot Nothing Then
                            errorMsg += ex.InnerException.Message
                        End If

                        Microsoft.VisualBasic.MsgBox(errorMsg, Microsoft.VisualBasic.MsgBoxStyle.Critical, _
                                                     "FileTransferProfile Application")
                    End Try

                    Exit Select

                Case "Push File Async"

                    If openFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then

                        If Not String.IsNullOrEmpty(openFileDialog1.FileName) Then
                            ftpManager1.SendFileAsync(openFileDialog1.FileName, Nothing)
                        End If

                    End If

                    Exit Select

                Case "Push Folder Sync"
                    Try

                        isAsync = False
                        If folderBrowserDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then

                            If Not String.IsNullOrEmpty(folderBrowserDialog1.SelectedPath) Then

                                ftpManager1.SendFolder(folderBrowserDialog1.SelectedPath)
                                Microsoft.VisualBasic.MsgBox("Synchronous Send Folder Operation Completed. " _
                                                             & Environment.NewLine & "Pushed Folder: " _
                                                             & folderBrowserDialog1.SelectedPath, _
                                                             Microsoft.VisualBasic.MsgBoxStyle.Information, _
                                                             "FileTransferProfile Application")
                            End If

                        End If

                    Catch ex As Exception

                        Dim errorMsg As String = "A Synchronous Send Folder Operation has failed. Error details: " & ex.Message

                        If ex.InnerException IsNot Nothing Then
                            errorMsg += ex.InnerException.Message
                        End If

                        Microsoft.VisualBasic.MsgBox(errorMsg, Microsoft.VisualBasic.MsgBoxStyle.Critical, _
                                                     "FileTransferProfile Application")
                    End Try

                    Exit Select

                Case "Push Folder Async"

                    If folderBrowserDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then

                        If Not String.IsNullOrEmpty(folderBrowserDialog1.SelectedPath) Then
                            ftpManager1.SendFolderAsync(folderBrowserDialog1.SelectedPath, Nothing)
                        End If

                    End If

                    Exit Select

            End Select

        End Sub

        ' Event Handler for btnExit Click event.Exits the application after disconnecting from the service.
        Private Sub btnExit_Click(ByVal sender As Object, ByVal e As EventArgs) _
                                                                Handles btnExit.Click

            Try

                If ftpManager1.NetworkStream IsNot Nothing Then
                    ftpManager1.Disconnect()
                End If

                If FTPService IsNot Nothing Then
                    FTPService.Disconnect()
                End If

            Catch ex As Exception

                If TypeOf ex Is C4F.DevKit.Bluetooth.FileTransferProfile.FTPException _
                OrElse TypeOf ex.InnerException Is C4F.DevKit.Bluetooth.FileTransferProfile.FTPException Then

                    Microsoft.VisualBasic.MsgBox("An Error occured while disconnecting from File Transfer Service on " _
                                                 & "remote device. " & ex.Message, _
                                                 Microsoft.VisualBasic.MsgBoxStyle.Critical, _
                                                 "FileTransferProfile Application")
                Else
                    Microsoft.VisualBasic.MsgBox("An Error occured while disconnecting from remote device. " _
                                                 & ex.Message, Microsoft.VisualBasic.MsgBoxStyle.Critical, _
                                                 "FileTransferProfile Application")

                End If

            Finally
                Me.Close()
            End Try

        End Sub

        ' Event Handler for btnRefreshFold Click event.Sets current directory to that of root.
        Private Sub btnRefreshFold_Click _
        (ByVal sender As Object, ByVal e As EventArgs) Handles btnRefreshFold.Click
            ' Sets the current directory to that of root.

            Try
                Me.Cursor = Cursors.WaitCursor
                ftpManager1.SetCurrentDirectory("\")
                tvFolderHierarchy.Nodes.Clear()
                Dim node As New TreeNode("\")
                node.Tag = "folder"
                tvFolderHierarchy.Nodes.Add(node)
                txtCurrentDirectory.Text = "\"

            Catch ex As Exception

                Dim errorMsg As String = ex.Message
                If ex.InnerException IsNot Nothing Then
                    errorMsg += ex.InnerException.Message
                End If

                Microsoft.VisualBasic.MsgBox("Error in Setting current directory to that of root directory. " _
                                             & errorMsg, Microsoft.VisualBasic.MsgBoxStyle.Critical, _
                                             "FileTransferProfile Application")

            Finally
                Me.Cursor = Cursors.Default
            End Try

        End Sub

#End Region

#Region "Private Functions"

        ' Gets the folder listing of current directory.
        Private Sub GetFolderListing(ByVal Path As String)

            Try
                Dim folderlisting As Xml.XmlDocument = ftpManager1.GetFolderListing(Path)
                txtCurrentDirectory.Text = Path
                If folderlisting IsNot Nothing Then

                    ' Get a list of folders
                    Dim folderList As Xml.XmlNodeList = folderlisting.GetElementsByTagName("folder")
                    ' Get a list of files
                    Dim fileList As Xml.XmlNodeList = folderlisting.GetElementsByTagName("file")
                    ' For each file in the list get its contents and then create a file on local
                    ' device with received file content.

                    If fileList IsNot Nothing AndAlso fileList.Count <> 0 Then

                        For Each node As Xml.XmlNode In fileList

                            Dim attrCollection As Xml.XmlAttributeCollection = node.Attributes

                            If attrCollection IsNot Nothing AndAlso attrCollection.Count <> 0 Then

                                Dim attrNode As Xml.XmlNode = attrCollection.GetNamedItem("name")

                                If attrNode IsNot Nothing Then

                                    Dim trvNode As New TreeNode(attrNode.Value)
                                    trvNode.Tag = "file"
                                    selectedNode.Nodes.Add(trvNode)

                                End If

                            End If

                        Next

                    End If

                    ' For each folder in the list create a folder on local device.
                    If folderList IsNot Nothing AndAlso folderList.Count <> 0 Then

                        For Each node As Xml.XmlNode In folderList
                            Dim attrCollection As Xml.XmlAttributeCollection = node.Attributes

                            If attrCollection IsNot Nothing AndAlso attrCollection.Count <> 0 Then

                                Dim attrNode As Xml.XmlNode = attrCollection.GetNamedItem("name")
                                If attrNode IsNot Nothing Then

                                    Dim trvNode As New TreeNode(attrNode.Value)
                                    trvNode.Tag = "folder"
                                    Dim isPresent As Boolean = False
                                    For Each trvChildNode As TreeNode In selectedNode.Nodes

                                        If trvChildNode.Text = trvNode.Text Then
                                            isPresent = True
                                            Exit For
                                        End If

                                    Next

                                    If Not isPresent Then
                                        selectedNode.Nodes.Add(trvNode)
                                    End If

                                End If

                            End If

                        Next

                    End If

                End If

            Catch ex As Exception

                Dim errorMsg As String = ex.Message
                If ex.InnerException IsNot Nothing Then
                    errorMsg += ex.InnerException.Message
                End If

                Microsoft.VisualBasic.MsgBox(errorMsg, Microsoft.VisualBasic.MsgBoxStyle.Critical, _
                                             "FileTransferProfile Application")
            End Try

        End Sub

#End Region


    End Class

End Namespace
